package com.wy.controller.wy;

import com.wy.bean.HouseholdBean;
import com.wy.constants.CommonValues;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import com.wy.service.wy.HouseholdService;
import com.wy.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Auther: tracy
 * @Date: 2018/8/20 16:58
 * @Description: 住户管理
 */
@RestController
public class HouseholdController {

	private Logger log = LoggerFactory.getLogger(HouseholdController.class);

	@Resource(name = "householdServiceImpl")
	private HouseholdService householdService;
	@Resource(name = "userServiceImpl")
	private UserService userService;
	@Autowired
	private CommonValues commonValues;

	/**
	 * 获取住户表数据
	 * 获取身份认证数据
	 * @param pageSize
	 * @param page
	 * @param residenceId 小区ID
	 * @param buildingId 楼栋ID
	 * @param houseId 房屋ID
	 * @param householdName 房主姓名
	 * @param plateNum 车牌号
	 * @return
	 */
	@GetMapping("/households")
	public PageResult householdList(HttpServletRequest request,@RequestParam(value="pageSize",required=false) Integer pageSize,
									@RequestParam(value="page",required=false) Integer page,
									@RequestParam(value="residenceId",required=false) Integer residenceId,
									@RequestParam(value="buildingId",required=false) Integer buildingId,
									@RequestParam(value="houseId",required=false) Integer houseId,
									@RequestParam(value="householdName",required=false) String householdName,
									@RequestParam(value="authStatus",required=false) String authStatus,
									@RequestParam(value="mobile",required=false) String mobile,
									@RequestParam(value="plateNum",required=false) String plateNum
									) {
		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){
				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}
		PageResult pageResult = new PageResult();
		if("admin".equals(userEntity.getLoginName())) {
			rids = null;
		}else {
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}
		pageResult.setData(householdService.householdList((page+1) * pageSize, page * pageSize, residenceId, buildingId, houseId, householdName, authStatus, mobile, plateNum,rids));
		pageResult.setTotalCount(householdService.householdSize((page+1) * pageSize, page * pageSize, residenceId, buildingId, houseId, householdName, authStatus, mobile, plateNum,rids));
		return pageResult;
	}

	/**
	 * 新建住户信息
	 * @param householdEntity
	 * @return
	 */
	@PostMapping("/households/household")
	public BaseResponseInfo insertHousehold(@RequestBody HouseholdBean householdEntity) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		//判断当前用户是否已经在该房注册过
		List<HouseholdBean> list =householdService.getHouseholdByHidCreNo(householdEntity.getHouseId(),householdEntity.getCredentialNo());
		if(null != list && list.size() >0) {
			baseResponseInfo.data = "该用户身份证已绑定此房屋，请确认信息！";
			baseResponseInfo.code = 500;
			return baseResponseInfo;
		}
		String message = householdService.insertHousehold(householdEntity);
		if(!StringUtils.isEmpty(message)){
			baseResponseInfo.data = message;
			baseResponseInfo.code = 500;
		}
		return baseResponseInfo;
	}

	/**
	 * 修改住户信息
	 *
	 * @param householdEntity
	 * @param id
	 * @return
	 */
	@PutMapping("/households/{id}")
	public BaseResponseInfo updateHousehold(@RequestBody HouseholdBean householdEntity, @PathVariable int id) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		if(householdEntity.getId() != id) {
			baseResponseInfo.data = "数据异常，请核查！";
			baseResponseInfo.code = 500;
			return baseResponseInfo;
		}
		//如果修改的身份证号码和房屋信息已经存在，且不是当前住户的，返回异常
		List<HouseholdBean> list =householdService.getHouseholdByHidCreNo(householdEntity.getHouseId(),householdEntity.getCredentialNo());
		if(null != list && list.size() >0) {
			HouseholdBean householdExist = list.get(0);
			if(householdExist.getId() !=id){
				baseResponseInfo.data = "该用户身份证已绑定此房屋，请确认信息！";
				baseResponseInfo.code = 500;
				return baseResponseInfo;
			}
		}
		householdService.updateHousehold(householdEntity);
		log.debug("The method is ending");
		return baseResponseInfo;
	}

	/**
	 * 删除住户信息
	 *
	 * @param groupId
	 * @return
	 */
	@DeleteMapping("/households")
	public void deleteHouseholds(@RequestBody List<String> groupId) {
		householdService.deleteHouseholds(groupId);
	}

	/**
	 * 批量导入业主接口（无验证）
	 * @param householdEntity
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save_household")
	public BaseResponseInfo saveHousehold(@RequestBody HouseholdBean householdEntity) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			householdEntity.setCreater("admin");
			householdEntity.setCreateTime(new Date());
			householdEntity.setStatus("1");
			householdService.insertHousehold(householdEntity);
			baseResponseInfo.code = HTTPStatus.OK;
			data.put("message", ConstantData.MSG_SUCCESS_INFO);
		} catch (Exception ex){
			ex.printStackTrace();
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
		}
		baseResponseInfo.data = data;
		return baseResponseInfo;
	}

	/**
	 * web端,移动端上传图片
	 * @param file
	 * @return
	 */
	@PostMapping("/households/uploadImg")
	public BaseResponseInfo uploadImage(HttpServletRequest request,List<MultipartFile> file,String path) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String, Object> data = new HashMap<String, Object>();
		if (file.isEmpty()) {
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
			return baseResponseInfo;
		}

		for (MultipartFile multipartFile : file) {
			if (multipartFile.isEmpty()) {
				continue;
			}
			String fileName = UUIDUtils.getUUID()+".jpg";
			File dest = new File(commonValues.getBasePath() + fileName);
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				multipartFile.transferTo(dest);//保存文件
				//不管什么图片都转成jpg
				ImageUtils.convertJPG(commonValues.getBasePath()+fileName,commonValues.getBasePath()+fileName);
				data.put("fileName",String.format(commonValues.getImgPath(),fileName));
				if(StringUtils.isEmpty(path)){
					data.put("pathReturn",commonValues.getOutsidePath());
				}else{
					data.put("pathReturn",path);
				}
			} catch (IOException e) {
				e.printStackTrace();
				baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
				return baseResponseInfo;
			}
		}

		baseResponseInfo.data = data;
		return baseResponseInfo;
	}

	/**
	 * 手机端注册补全信息
	 * @param userId 登录的用户ID，对应表sys_user 的id
	 * @param houseId 房屋ID
	 * @param householdName 屋主姓名
	 * @param gender 性别
	 * @param birthDate 生日
	 * @param address 详细地址
	 * @param peopleType 户籍类别：1.户籍人员2.外来人员3.境外人员
	 * @param company 工作单位
	 * @param department 工作部门
	 * @param identityType 身份类型1:业主,2家属,3租客
	 * @param credentialType 证件类型10.身份证14.普通护照15.驾驶证
	 * @param credentialNo 证件号码
	 * @param idCardImage1 身份证图片
	 * @param idCardImage2 身份证图片
	 * @param facePic 人脸采集图片(当前照片)
	 * @param ext3 拟住时间
	 * @param ext4 标签
	 * @param nation 民族
	 * @param familyMembers 家属信息json[{"householdName":"小明","gender","男","birthDate":"1990-09-01","credentialNo":"xxxxxxx","mobile":"137xxxxx","memberRealtion":"子"}]
	 * @param carInfos 车辆信息["车牌号1","车牌号2"] 最多5个
	 * @param ext5 门禁卡号
	 * @param houseOwnerName 屋主姓名，当前注册人是房客时使用
	 * @param houseOwnerCredentialNo 屋主身份证，当前注册人是房客时使用
	 * @param houseOwnerMobile 屋主手机号，当前注册人是房客时使用
	 * @param currentUserId 当前记录的人
	 * @param mobile 手机号
	 * @return
	 */
	@PostMapping("/households/register")
	@ResponseBody
	public BaseResponseInfo registerStep1(@RequestParam("userId") Integer userId,
										  @RequestParam("houseId") Integer houseId,
										  @RequestParam("householdName") String householdName,
										  @RequestParam("gender") String gender,
										  @RequestParam("birthDate") String birthDate,
										  @RequestParam("address") String address,
										  @RequestParam("peopleType") String peopleType,
										  @RequestParam("company") String company,
										  @RequestParam("department") String department,
										  @RequestParam("identityType") String identityType,
										  @RequestParam("credentialType") String credentialType,
										  @RequestParam("credentialNo") String credentialNo,
										  @RequestParam("idCardImage1") String idCardImage1,
										  @RequestParam("idCardImage2") String idCardImage2,
										  @RequestParam("facePic") String facePic,
										  @RequestParam("ext3") String ext3,
										  @RequestParam("ext4") String ext4,
										  @RequestParam("nation") String nation,
										  @RequestParam(value = "familyMembers",required = false) String familyMembers,
										  @RequestParam(value = "carInfos",required = false) String carInfos,
										  @RequestParam(value = "ext5",required = false) String ext5,
										  @RequestParam(value = "houseOwnerName",required = false) String houseOwnerName,
										  @RequestParam(value = "houseOwnerCredentialNo",required = false) String houseOwnerCredentialNo,
										  @RequestParam(value = "houseOwnerMobile",required = false) String houseOwnerMobile,
										  @RequestParam(value = "currentUserId",required = false) Integer currentUserId,
										  @RequestParam(value = "mobile",required = false) String mobile,
										  @RequestParam(value = "memberRelation",required = false) String memberRelation
	){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String,String> result = new HashMap<String,String>();
//		if(null == userId){
//			baseResponseInfo.code = 500;
//			result.put("message","无效的用户ID");
//			baseResponseInfo.data = result;
//			return baseResponseInfo;
//		}
//		UserEntity currentUser = userService.getUserById(userId);
//		if(null == currentUser) {
//			baseResponseInfo.code = 500;
//			result.put("message","未查到用户，请先注册");
//			baseResponseInfo.data = result;
//			return baseResponseInfo;
//		}
		if(null == houseId ) {
			baseResponseInfo.code = 500;
			result.put("message","房屋id为空！");
			baseResponseInfo.data = result;
			return baseResponseInfo;
		}
		baseResponseInfo.data = householdService.registerHousehold(userId,houseId,householdName,gender,birthDate,address,
				peopleType,company,department,identityType,credentialType,
				credentialNo,idCardImage1,idCardImage2,facePic,ext3,ext4,
				nation,familyMembers,carInfos,ext5,houseOwnerName,houseOwnerCredentialNo,houseOwnerMobile,currentUserId,mobile,memberRelation);
		return baseResponseInfo;
	}

	/**
	 * 批量认证住户信息
	 * @param groupId
	 * @return
	 */
	@PostMapping("/authHousehoulds")
	public BaseResponseInfo authHousehoulds(@RequestBody List<String> groupId){
			BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
			Map<String,String> map = new HashMap<>();
			householdService.authHousehoulds(groupId);
			baseResponseInfo.data = map;
			return baseResponseInfo;
	}

	/**
	 * 获取用户所有的房屋信息
	 */
	@GetMapping("/households/query_houses_userId")
	public PageResult queryHousesByUserId(Integer userId ){
		PageResult pageResult = new PageResult();
		pageResult.setData(householdService.getHouseHoldByUserId(userId));
		return pageResult;
	}

	@GetMapping("/households/download")
	public void download(HttpServletRequest request, HttpServletResponse response,
						 @RequestParam(value="residenceId",required=false) Integer residenceId,
						 @RequestParam(value="buildingId",required=false) Integer buildingId,
						 @RequestParam(value="houseId",required=false) Integer houseId,
						 @RequestParam(value="householdName",required=false) String householdName,
						 @RequestParam(value="authStatus",required=false) String authStatus,
						 @RequestParam(value="mobile",required=false) String mobile,
						 @RequestParam(value="plateNum",required=false) String plateNum,String username) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename="+new String( "住户信息.xls".getBytes("gb2312"), "ISO8859-1" ));

		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(username);
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){

				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}

		List<HouseholdBean> list = new ArrayList<>();
		if("admin".equals(username)) {
			rids = null;
		}else {
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}
		list = householdService.householdList(null, null, residenceId, buildingId, houseId, householdName, authStatus, mobile, plateNum, rids);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), HouseholdBean.class, list);
		workbook.write(response.getOutputStream());
	}

	/**
	 * 数据导入
	 * @param file
	 */
	@PostMapping("/households/import")
	public void importExcel(MultipartFile file){
		List<HouseholdBean> householdList = FileUtil.importExcel(file,0,1,HouseholdBean.class);
		System.out.println("导入数据一共【"+householdList.size()+"】行");
		if(householdList != null) {
			householdService.insertBatch(householdList);
		}else{

		}
	}

	/**
	 * 根据房屋id获取房屋下所有的住户
	 * @param houseId
	 * @return
	 */
	@PostMapping("/households/families")
	public BaseResponseInfo getWholeFamily(Integer houseId) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		if(null == houseId) {
			baseResponseInfo.code = 500;
			baseResponseInfo.data = "houseID 不能为空！";
			return baseResponseInfo;
		}
		baseResponseInfo.data = householdService.getHouseholdByHid(houseId);
		return baseResponseInfo;
	}

}
